#!/bin/bash
# 安装配置
apt install -y bind9
#添加正向解析
domain=$(whiptail --title "Configure DNS" --inputbox "Please input your domain" 10 60 example.com 3>&1 1>&2 2>&3)
local_ip=$(whiptail --title "Configure DNS" --inputbox "Please input your local ip related to $domian" 10 60 192.168.111.11 3>&1 1>&2 2>&3)
#定义为全局变量
echo "export DOMAIN=$domain
export LOCAL_IP=$local_ip
# 配置开机自动配置本地DNS
cat /etc/resolv.conf|grep $local_ip 1>/dev/null
if [ \$? -ne 0 ];then
  sed \"2a namerserver $local_ip\" -i /etc/resolv.conf
fi" >> /etc/profile.d/my.sh
chmod 755 /etc/profile.d/my.sh
cat /etc/profile.d/my.sh
source /etc/profile
cat /etc/resolv.conf
#创建正向解析
echo "\$TTL    604800
@       IN      SOA     example.com. root.localhost. (
                              1         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
@       IN      NS      localhost.
example.com IN      NS      $local_ip
www     IN      A       $local_ip
mail     IN     A       $local_ip
@       IN      MX      10      mail
app1     IN      CNAME   www
ns     IN      CNAME   www
app2     IN      CNAME   www
java     IN      CNAME   www" >/etc/bind/db.${DOMAIN}

#配置反向解析
reverse_ip=$(whiptail --title "Configure DNS" --inputbox "Please input your reverse ip" 10 60 111.168.192 3>&1 1>&2 2>&3)
host_id=$(whiptail --title "Configure DNS" --inputbox "Please input your host id" 10 60 100 3>&1 1>&2 2>&3)
echo "\$TTL 43200;
@  IN  SOA ${reverse_ip}.in-addr.arpa. localhost. (
        1
        1h
        5m
        7d
        1d)
@   IN  NS  ${DOMAIN}.
${host_id}  IN  PTR www.${DOMAIN}.
${host_id}  IN  PTR mail.${DOMAIN}.
${host_id}  IN  PTR ns.${DOMAIN}.
${host_id}  IN  PTR app1.${DOMAIN}.
${host_id}  IN  PTR app2.${DOMAIN}.
${host_id}  IN  PTR java.${DOMAIN}." >/etc/bind/${reverse_ip}.zone

# 检查语法
named-checkzone db.${DOMAIN} /etc/bind/db.${DOMAIN}
named-checkzone ${host_id}.in-addr.arpa /etc/bind/${host_id}.zone

#配置区域解析文件
echo "zone \"${domain}\" IN {
        type master;
        file \"/etc/bind/db.${domain}\";
};
zone \"${reverse_ip}.in-addr.arpa\" IN {
        type master;
        file \"/etc/bind/${reverse_ip}.zone\";
};" >> /etc/bind/named.conf.local

systemctl restart bind9

echo "Check domain name validity:"
nslookup $domain
echo "Check reverse ip validity:"
nslookup $local_ip
